package com.example.ymq

import android.content.Context
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.material3.Button
import androidx.compose.material3.AlertDialog
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.ymq.ui.theme.YMQTheme
import java.io.IOException
import java.util.concurrent.TimeUnit
import kotlinx.coroutines.launch
import androidx.lifecycle.lifecycleScope
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.FormBody
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import androidx.compose.runtime.rememberCoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import com.example.ymq.data.*

// 添加以下导入
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.platform.LocalContext
import kotlinx.coroutines.flow.first
// 添加导入
import android.content.res.AssetManager
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExposedDropdownMenuBox
import androidx.compose.material3.ExposedDropdownMenuDefaults
import androidx.compose.runtime.mutableStateOf
import com.google.gson.Gson
import androidx.compose.material3.TextField
import android.app.DatePickerDialog
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import java.time.LocalDate
import java.time.format.DateTimeFormatter

// Add this before MainActivity class
private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")

class MainActivity : ComponentActivity() {
    @RequiresApi(Build.VERSION_CODES.O)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            YMQTheme {
                Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
                    Greeting(modifier = Modifier.padding(innerPadding).padding(16.dp))
                }
            }
        }
    }
}



data class VenueData(
    val status: Int,
    val info: String,
    val data: VenueDetail
)

data class VenueDetail(
    val venue_id: String,
    val area: List<Area>,
    val auth_role: Int
)

data class Area(
    val area_id: Int,
    val area_name: String,
    val range: String,
    val preview: String
)

@RequiresApi(Build.VERSION_CODES.O)
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun Greeting(modifier: Modifier = Modifier) {
    val context = LocalContext.current
    val scope = rememberCoroutineScope()
    var showDialog by remember { mutableStateOf(false) }
    var responseText by remember { mutableStateOf("") }
    var venueData by remember { mutableStateOf<VenueData?>(null) }
    var expanded by remember { mutableStateOf(false) }
    
    LaunchedEffect(Unit) {
        try {
            val inputStream = context.assets.open("data.json")
            val jsonString = inputStream.bufferedReader().use { it.readText() }
            venueData = Gson().fromJson(jsonString, VenueData::class.java)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
    
    // 定义 preferences keys
    val PHPSESSID = stringPreferencesKey("phpsessid")
    val TIMESTAMP = stringPreferencesKey("timestamp")
    val H5_TOKEN = stringPreferencesKey("h5token")
    val UID = stringPreferencesKey("uid")
    val CHANGDI = stringPreferencesKey("changdi")
    val DAY = stringPreferencesKey("day")
    
    var phpsessid by remember { mutableStateOf("") }
    var timestamp by remember { mutableStateOf("") }
    var h5_token by remember { mutableStateOf("") }
    var uid by remember { mutableStateOf("") }
    var changdi by remember { mutableStateOf("") }
    var day by remember { mutableStateOf("") }
    
    // 加载保存的值
    LaunchedEffect(Unit) {
        context.dataStore.data.first().let { preferences ->
            phpsessid = preferences[PHPSESSID] ?: ""
            timestamp = preferences[TIMESTAMP] ?: ""
            h5_token = preferences[H5_TOKEN] ?: ""
            uid = preferences[UID] ?: ""
            changdi = preferences[CHANGDI] ?: ""
            day = preferences[DAY] ?: ""
        }
    }

    Column(modifier = modifier) {
        OutlinedTextField(
            value = phpsessid,
            onValueChange = { 
                phpsessid = it
                scope.launch {
                    context.dataStore.edit { preferences ->
                        preferences[PHPSESSID] = it
                    }
                }
            },
            label = { Text("PHPSESSID") }
        )
        Spacer(modifier = Modifier.height(8.dp))
        OutlinedTextField(
            value = uid,
            onValueChange = {
                uid = it
                scope.launch {
                    context.dataStore.edit { preferences ->
                        preferences[UID] = it
                    }
                }
            },
            label = { Text("UID") }
        )
        Spacer(modifier = Modifier.height(8.dp))
        OutlinedTextField(
            value = timestamp,
            onValueChange = { 
                timestamp = it
                scope.launch {
                    context.dataStore.edit { preferences ->
                        preferences[TIMESTAMP] = it
                    }
                }
            },
            label = { Text("Timestamp") }
        )
        Spacer(modifier = Modifier.height(8.dp))

        OutlinedTextField(
            value = h5_token,
            onValueChange = { 
                h5_token = it
                scope.launch {
                    context.dataStore.edit { preferences ->
                        preferences[H5_TOKEN] = it
                    }
                }
            },
            label = { Text("h5_token") }
        )
        Spacer(modifier = Modifier.height(8.dp))



        ExposedDropdownMenuBox(
            expanded = expanded,
            onExpandedChange = { expanded = it }
        ) {
            OutlinedTextField(
                value = changdi,
                onValueChange = {},
                readOnly = true,
                trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) },
                modifier = Modifier.menuAnchor(),
                label = { Text("选择场地") }
            )
            ExposedDropdownMenu(
                expanded = expanded,
                onDismissRequest = { expanded = false }
            ) {
                venueData?.data?.area?.forEach { area ->
                    DropdownMenuItem(
                        text = { Text(area.area_name) },
                        onClick = {
                            changdi = area.area_name
                            scope.launch {
                                context.dataStore.edit { preferences ->
                                    preferences[CHANGDI] = area.area_name
                                }
                            }
                            expanded = false
                        }
                    )
                }
            }
        }
        Spacer(modifier = Modifier.height(8.dp))

        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceEvenly
        ) {
            Button(
                onClick = {
                    try {
                        val currentDate = if (day.isNotEmpty()) {
                            try {
                                LocalDate.parse(day)
                            } catch (e: Exception) {
                                LocalDate.now()
                            }
                        } else {
                            LocalDate.now()
                        }
                        DatePickerDialog(
                            context,
                            { _, year, month, dayOfMonth ->
                                try {
                                    val selectedDate = LocalDate.of(year, month + 1, dayOfMonth)
                                    val formattedDate = selectedDate.format(
                                        DateTimeFormatter.ofPattern("yyyy-MM-dd")
                                    )
                                    val dayOfWeek = selectedDate.dayOfWeek.value
                                    val weekMsg = when(dayOfWeek) {
                                        1 -> "周一"
                                        2 -> "周二"
                                        3 -> "周三"
                                        4 -> "周四"
                                        5 -> "周五"
                                        6 -> "周六"
                                        7 -> "周日"
                                        else -> ""
                                    }
                                    day = formattedDate
                                    scope.launch {
                                        context.dataStore.edit { preferences ->
                                            preferences[DAY] = formattedDate
                                        }
                                    }
                                } catch (e: Exception) {
                                    val today = LocalDate.now()
                                    day = today.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))
                                }
                            },
                            currentDate.year,
                            currentDate.monthValue - 1,
                            currentDate.dayOfMonth
                        ).show()
                    } catch (e: Exception) {
                        val today = LocalDate.now()
                        day = today.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))
                    }
                }
            ) {
                Text("选择日期")
            }
            
            Button(onClick = { 
                scope.launch {
                    try {
                        val config = Config(
                            cookies = Cookies(PHPSESSID = phpsessid),
                            auth = Auth(
                                h5_token = h5_token,
                                uid = uid,
                                timestamp = timestamp
                            )
                        )

                        val timeSlots = listOf(
                            TimeSlot("18:00-19:00", 22071),
                            TimeSlot("19:00-20:00", 22072),
                            TimeSlot("20:00-21:00", 22073)
                        )

                        val reservation = Reservation(
                            date = day,
                            time_slots = timeSlots
                        )

                        val selectedArea = venueData?.data?.area?.find { it.area_name == changdi }
                        val areaId = selectedArea?.area_id?.toString() ?: ""

                        val selectedDate = LocalDate.parse(reservation.date)
                        val dayOfWeek = selectedDate.dayOfWeek.value
                        val weekMsg = when(dayOfWeek) {
                            1 -> "周一"
                            2 -> "周二"
                            3 -> "周三"
                            4 -> "周四"
                            5 -> "周五"
                            6 -> "周六"
                            7 -> "周日"
                            else -> ""
                        }
                        
                        val details = reservation.time_slots.mapIndexed { index, slot ->
                            ReservationDetail(
                                date = reservation.date,
                                area_name = changdi,
                                interval_time = slot.time,
                                interval_id = slot.interval_id.toString(),
                                area_id = areaId,
                                week = dayOfWeek,
                                week_msg = weekMsg
                            )
                        }

                        val reservationData = ReservationData(
                            stadium_id = reservation.stadium_id.toString(),
                            venue_id = reservation.venue_id.toString(),
                            details = details,
                            timestamp = config.auth.timestamp,
                            h5_token = config.auth.h5_token,
                            uid = config.auth.uid
                        )

                        val client = OkHttpClient.Builder()
                            .connectTimeout(30, TimeUnit.SECONDS)
                            .readTimeout(30, TimeUnit.SECONDS)
                            .build()
                        
                        val jsonBody = Gson().toJson(reservationData)
                        val requestBody = jsonBody.toRequestBody("application/json; charset=utf-8".toMediaType())

                        val request = Request.Builder()
                            .url(config.baseUrl + config.endpoint)
                            .addHeader("User-Agent", "Mozilla/5.0 (Linux; Android 14 wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/114.0.5735.196 Mobile Safari/537.36")
                            .addHeader("Content-Type", "application/json; charset=UTF-8")
                            .addHeader("X-Requested-With", "XMLHttpRequest")
                            .addHeader("Cookie", "PHPSESSID=${config.cookies.PHPSESSID}")
                            .post(requestBody)
                            .build()
                        
                        withContext(Dispatchers.IO) {
                            try {
                                client.newCall(request).execute().use { response ->
                                    if (response.isSuccessful) {
                                        responseText = response.body?.string() ?: "No response body"
                                    } else {
                                        responseText = "Request failed: ${response.code}"
                                    }
                                }
                            } catch (e: IOException) {
                                responseText = "Network error: ${e.message}"
                            }
                        }
                        showDialog = true
                    } catch (e: Exception) {
                        responseText = "Error: ${e.message}\n${e.stackTraceToString()}"
                        showDialog = true
                    }
                }
            }) {
                Text("发送请求")
            }
            
            Button(
                onClick = {
                    val data = buildString {
                        appendLine("构建的Data对象：")
                        appendLine("预约信息：")
                        appendLine("- 日期：$day")
                        appendLine("- 场地：$changdi")
                        appendLine("\n时间段：")
                        appendLine("- 18:00-19:00 (ID: 22071)")
                        appendLine("- 19:00-20:00 (ID: 22072)")
                        appendLine("- 20:00-21:00 (ID: 22073)")
                        appendLine("\n认证信息：")
                        appendLine("- PHPSESSID: $phpsessid")
                        appendLine("- UID: $uid")
                        appendLine("- Timestamp: $timestamp")
                        appendLine("- h5_token: $h5_token")
                    }
                    responseText = data
                    showDialog = true
                }
            ) {
                Text("查看Data")
            }
        }
        
        if (showDialog) {
            AlertDialog(
                onDismissRequest = { showDialog = false },
                title = { Text("服务器响应") },
                text = {
                    Text(responseText)
                },
                confirmButton = {
                    Button(onClick = { showDialog = false }) {
                        Text("确定")
                    }
                }
            )
        }
    }
}
